#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2;
constexpr int16_t Shift = 8;
class KernelL1loss {
public:
    __aicore__ inline KernelL1loss() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR s, uint32_t reduction,const L1lossTilingData &tiling_data) 
    {
        this->tiling=tiling_data;
        this->reduction=reduction;
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = tiling.bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = tiling.ubPartDataNum;
        if (tiling.tailBlockNum!=0) 
        {
          if (coreNum < tiling.tailBlockNum) 
          { 
            this->coreDataNum = tiling.bigCoreDataNum;
            this->tileNum = tiling.bigCoreLoopNum;
            this->tailDataNum = tiling.bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = tiling.smallCoreDataNum;
            this->tileNum = tiling.smallCoreLoopNum;
            this->tailDataNum = tiling.smallCoreTailDataNum;
            globalBufferIndex -= (tiling.bigCoreDataNum - tiling.smallCoreDataNum) * (AscendC::GetBlockIdx() - tiling.tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = tiling.smallCoreDataNum;
          this->tileNum = tiling.smallCoreLoopNum;
          this->tailDataNum = tiling.smallCoreTailDataNum;
          globalBufferIndex = tiling.smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ float*)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ float*)y + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ float*)z + globalBufferIndex, this->coreDataNum);
        sGm.SetGlobalBuffer((__gm__ float *)s ,tiling.slength);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(outQueueS, BUFFER_NUM, tiling.slength* sizeof(float));
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;
        for (int32_t i = 0; i < loopCount-1; i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;
        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
      AscendC::LocalTensor<float> yLocal = inQueueY.AllocTensor<float>();

      AscendC::DataCopy(xLocal, xGm[progress * this->processDataNum], this->processDataNum);
      AscendC::DataCopy(yLocal, yGm[progress * this->processDataNum], this->processDataNum);

      inQueueX.EnQue(xLocal);
      inQueueY.EnQue(yLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
      AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
      AscendC::LocalTensor<float> yLocal = inQueueY.DeQue<float>();
      AscendC::LocalTensor<float> zLocal = outQueueZ.AllocTensor<float>();
      AscendC::LocalTensor<float> sLocal = outQueueS.AllocTensor<float>();

      this->reduction=1;
      if(reduction == 0)
      {//none
          AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
          AscendC::Abs(zLocal, zLocal, this->processDataNum);
      }
      else if(reduction == 1)
      {//sum
        AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
        AscendC::Abs(zLocal, zLocal, this->processDataNum);
        // 进行归约
        for (int i = 0 ; i <this->processDataNum; i++) {
            float temp = zLocal.GetValue(i);
            sum = temp+sum;
        }
        if(progress == this->tileNum - 1){
            sLocal.SetValue(0,sum);
        }
        }
        else if(reduction == 2) 
        {//mean
            AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
            AscendC::Abs(zLocal, zLocal, this->processDataNum);
            // 进行归约
            for (int i = 0 ; i < this->processDataNum; i++) {
                float temp = zLocal.GetValue(i);
                sum = temp+sum;
            }
            if(progress == this->tileNum - 1){
                sLocal.SetValue(0,sum/tiling.inputDataNum);
            }
        }

        outQueueZ.EnQue<float>(zLocal);
        outQueueS.EnQue<float>(sLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueY.FreeTensor(yLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
        if(reduction==0){
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
        AscendC::DataCopy(sGm, sLocal, tiling.slength);
        outQueueS.FreeTensor(sLocal);
        outQueueZ.FreeTensor(zLocal);
        }else if(reduction == 1){
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
        if(progress == this->tileNum - 1){
            AscendC::SetAtomicAdd<float>();
            AscendC::DataCopy(sGm, sLocal, tiling.slength);
            AscendC::SetAtomicNone();
        }
            outQueueS.FreeTensor(sLocal);
            outQueueZ.FreeTensor(zLocal);
        }else if(reduction ==2){
            AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
            AscendC::LocalTensor<float> sLocal = outQueueS.DeQue<float>();
            AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
            if(progress == this->tileNum - 1){
                AscendC::SetAtomicAdd<float>();
                AscendC::DataCopy(sGm, sLocal, tiling.slength);
                AscendC::SetAtomicNone();
            }
            outQueueS.FreeTensor(sLocal);
            outQueueZ.FreeTensor(zLocal);
        }
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueY;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueS;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmp1;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmp2;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    AscendC::GlobalTensor<float> zGm;
    AscendC::GlobalTensor<float> sGm;
    uint32_t reduction;
    float sum;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
    L1lossTilingData tiling;
};

extern "C" __global__ __aicore__ void l1loss_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z,GM_ADDR s, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);
    uint32_t reduction = 0;
    KernelL1loss op;
    op.Init(x, y, z, s , reduction, tiling_data);
    op.Process();
}

